﻿using System;
using System.Configuration;
using System.Web.Security;
using System.Web.UI.WebControls;

public partial class Registration : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        InvisibleCaptcha.InititializeCaptcha(this, ViewState);
    }
    protected void CreateUserWizard1_CreatingUser(object sender, LoginCancelEventArgs e)
    {
        InvisibleCaptcha.IsCaptchaValid(this, ViewState, true);
    }
    protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
    {
        string adminUsername = ConfigurationManager.AppSettings["AdminUsername"];
        string autoApprove = ConfigurationManager.AppSettings["AutoApproveNewUser"];

        //consider setting the DisableCreatedUser property of the CreateUserWizard
        if (autoApprove == "False")
        {
            MembershipUser newUser = Membership.GetUser(CreateUserWizard1.UserName);
            newUser.IsApproved = false;
            Membership.UpdateUser(newUser);
        }

        if(!String.IsNullOrEmpty(adminUsername))
        {
            if (CreateUserWizard1.UserName == adminUsername)
            {
                MembershipUser adminUser = Membership.GetUser(adminUsername);

                adminUser.IsApproved = true;

                if (!Roles.RoleExists(Constants.Roles.Admin))
                {
                    Roles.CreateRole(Constants.Roles.Admin);
                }

                Roles.AddUserToRole(adminUsername, Constants.Roles.Admin);

                Membership.UpdateUser(adminUser);
            }
        }

        //clear user list cache so new users are displayed in the user management
        Cache.Remove(Constants.Cache.Users);
    }
}
